package com.ruoyi.web.controller.qqLoginAndPayByHTQ;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.School.domain.School;
import com.ruoyi.School.service.ISchoolService;
import com.ruoyi.User.domain.User;
import com.ruoyi.User.service.IUserService;
import com.ruoyi.UserAddress.domain.UserAddress;
import com.ruoyi.UserAddress.service.IUserAddressService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.PhoneLoginService;
import com.ruoyi.system.weixin.AesCbcUtil;
import com.ruoyi.system.weixin.Httprequests;

/**
 * 用户 信息操作处理
 * 
 * @author hetianqi
 * @date 2019-07-25
 */
@Controller
@RequestMapping(value = "/a/data")
public class qqLoginController extends BaseController {
	/**
	 * 获取QQ小程序 session_key 和 openid
	 *
	 * @param code
	 *            调用QQ登陆返回的Code
	 * @return
	 */

	@Autowired
	private PhoneLoginService phoneLoginService;

	@RequestMapping(value = "/qqApi/login")
	@ResponseBody
	public Map<String, Object> getSessionKeyOropenid(
			@RequestParam(value = "code", required = true) String code,
			String encryptedData, String iv, HttpServletRequest request)
			throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();

		String sendGet = loginByQQ(code); // 根据code去调用接口获取用户openid和session_key
		JSONObject json = JSONObject.fromObject(sendGet);

		System.out.println("返回过来的json数据:" + json.toString());
		String sessionkey = json.get("session_key").toString(); // 会话秘钥
		String openid = json.get("openid").toString(); // 用户唯一标识
		Map<String, Object> ss = login(openid, request);
		int codes = Integer.parseInt(ss.get("code").toString());
		if (codes != 2) {
			return ss;
		} else {
			try {
				// 拿到用户session_key和用户敏感数据进行解密，拿到用户信息。
				String decrypts = AesCbcUtil.decrypt(encryptedData, sessionkey,
						iv, "utf-8");// 解密
				JSONObject jsons = JSONObject.fromObject(decrypts);
				String nickName = filterEmoji(jsons.get("nickName").toString()); // 用户昵称
				String jsonsds = jsons.get("avatarUrl").toString(); // 用户头像
				/*
				 * jsons.get("avatarUrl").toString(); //头像
				 * jsons.get("gender").toString();//性别
				 * jsons.get("unionid").toString(); //unionid
				 * jsons.get("city").toString(); //城市
				 * jsons.get("province").toString();//省份
				 * jsons.get("country").toString(); //国家
				 */
				return login_insert(openid, nickName, jsonsds, request);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		map.clear();
		map.put("code", 0);
		map.put("errorMsg", "错误!登陆服务器超时2");
		return map;
	}

	/**
	 * @author: niesui
	 * @methodsName: a/data/login
	 * @description: 登陆
	 * @param: openid nickname avater
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value = "/qqApi/ladder/login", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> login(
			@RequestParam(value = "openid", required = true) String openid,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		try {
			// 密钥随机生成
			UUID uuid = UUID.randomUUID();
			String key = uuid.toString();
			List<Map<String, Object>> list = phoneLoginService
					.CallShellProcedure("R2001001|" + openid + "|" + key);
			map = list.get(0);
			// id,nickname,avatar,school,specialty,faculty
			if (Integer.parseInt(map.get("codes").toString()) == 0) {
				map.clear();
				map.put("code", 2);
				map.put("errorMsg", "转到注册");
			} else {
				HttpSession session = request.getSession();
				session.setAttribute("accesstoken", key);
				session.setAttribute("uid", map.get("id"));
				session.setAttribute("nickname", map.get("nickname"));
				session.setAttribute("avatar", map.get("avatar"));
				session.setAttribute("renzheng", map.get("renzheng"));
				session.setAttribute("openid", openid);
				session.setAttribute("school", map.get("school"));
				session.setAttribute("specialty", map.get("specialty"));
				session.setAttribute("faculty", map.get("faculty"));
				map.clear();
				map.put("code", 1);
				map.put("uid", session.getAttribute("uid"));
				map.put("nickname", session.getAttribute("nickname"));
				map.put("avatar", session.getAttribute("avatar"));
				map.put("renzheng", session.getAttribute("renzheng"));
				map.put("accesstoken", key);
			}
		} catch (Exception e) {
			map.clear();
			map.put("code", 0);
			map.put("errorMsg", "错误!登陆服务器超时");
		}

		return map;
	}

	/**
	 * @author: niesui
	 * @methodsName: a/data/login
	 * @description: zhuce
	 * @param: openid nickname avater
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value = "/qqApi/ladder/login_insert")
	@ResponseBody
	public Map<String, Object> login_insert(
			@RequestParam(value = "openid", required = true) String openid,
			@RequestParam(value = "nickname", required = true) String nickname,
			@RequestParam(value = "avater", required = true) String avater,
			HttpServletRequest request) {
		UUID uuid = UUID.randomUUID();
		String key = uuid.toString();
		Map<String, Object> map = new HashMap<>();
		try {

			List<Map<String, Object>> list = phoneLoginService
					.CallShellProcedure("R2001001|" + openid + "|" + key);

			map = list.get(0);
			// id,nickname,avatar,school,specialty,faculty
			if (Integer.parseInt(map.get("codes").toString()) == 0) {
				List<Map<String, Object>> lists = phoneLoginService
						.CallShellProcedure("R2001002|" + openid + "|"
								+ nickname + "|" + avater + "|" + key);
				map = lists.get(0);
				HttpSession session = request.getSession();
				session.setAttribute("accesstoken", key);
				session.setAttribute("uid", map.get("id"));
				session.setAttribute("nickname", map.get("nickname"));
				session.setAttribute("avatar", map.get("avatar"));
				session.setAttribute("openid", openid);
				session.setAttribute("school", map.get("school"));
				session.setAttribute("specialty", map.get("specialty"));
				session.setAttribute("faculty", map.get("faculty"));
				map.clear();
				map.put("code", 1);
				map.put("uid", session.getAttribute("uid"));
				map.put("nickname", session.getAttribute("nickname"));
				map.put("renzheng", 0);
				map.put("avatar", session.getAttribute("avatar"));
				map.put("accesstoken", key);
			} else {
				HttpSession session = request.getSession();
				session.setAttribute("accesstoken", key);
				session.setAttribute("uid", map.get("id"));
				session.setAttribute("nickname", map.get("nickname"));
				session.setAttribute("avatar", map.get("avatar"));
				session.setAttribute("openid", openid);
				session.setAttribute("school", map.get("school"));
				session.setAttribute("specialty", map.get("specialty"));
				session.setAttribute("faculty", map.get("faculty"));
				map.clear();
				map.put("code", 1);
				map.put("uid", session.getAttribute("uid"));
				map.put("nickname", session.getAttribute("nickname"));
				map.put("avatar", session.getAttribute("avatar"));
				map.put("renzheng", 0);
				map.put("accesstoken", key);
			}
		} catch (Exception e) {
			map.clear();
			map.put("code", 0);
			map.put("errorMsg", "错误!登陆服务器超时");
		}

		return map;
	}

	public String loginByQQ(String code) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 小程序唯一标识 (在微信小程序管理后台获取)
		// 小程序唯一标识 (在微信小程序管理后台获取)
		String AppSecert = qqLoginConfig.AppSecert;
		// 小程序的 app secret (在微信小程序管理后台获取)
		String AppID = qqLoginConfig.AppID;
		// 授权（必填）
		String grant_type = "authorization_code";

		String params = "appid=" + AppID + "&secret=" + AppSecert + "&js_code="
				+ code + "&grant_type=" + grant_type;
		String urlss = "https://api.q.qq.com/sns/jscode2session"; // 获取用户的openid和session_key
		// 注意这个是 WeChatTool.wxspAppid 是微信小程序的appid 从微信小程序后台获取
		// WeChatTool.wxspSecret 这个也一样，我这里是用了常量来进行保存方便多次使用
		String sendGet = Httprequests.sendGet(urlss, params); // 发起请求拿到key和openid
		return sendGet;
	}

	public static String filterEmoji(String nick_name) {
		// nick_name 所获取的用户昵称
		if (nick_name == null) {
			return nick_name;
		}
		Pattern emoji = Pattern
				.compile(
						"[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff][\ue000-\uefff]",
						Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
		Matcher emojiMatcher = emoji.matcher(nick_name);
		if (emojiMatcher.find()) {
			// 将所获取的表情转换为*
			nick_name = emojiMatcher.replaceAll("");
			return nick_name;
		}
		return nick_name;
	}

}
